package com.searchit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Build.VERSION;
import android.text.Spannable;
import android.text.style.BackgroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;

import com.airpush.android.Airpush;

public class SearchIT extends Activity implements OnClickListener {
	/** Called when the activity is first created. */

	BufferedReader br;
	Spannable sText = null;
	EditText text;
	Stack<BackgroundColorSpan> bcs;
	private ArrayList<Integer> startingPositions;
	int currentPosition = -1;
	BackgroundColorSpan selectedColor;
	private File file;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(Integer.parseInt(VERSION.SDK) > 3) {
			new Airpush(getApplicationContext(),"10534","1302827800259757899");
		}
		
		setContentView(R.layout.main);

		startingPositions = new ArrayList<Integer>();
		selectedColor = new BackgroundColorSpan(Color.YELLOW);

		bcs = new Stack<BackgroundColorSpan>();
		text = ((EditText) findViewById(R.id.edit));
		
		fillTextField();

		findViewById(R.id.searchBtn).setOnClickListener(this);
		findViewById(R.id.prevBtn).setOnClickListener(this);
		findViewById(R.id.nextBtn).setOnClickListener(this);
		findViewById(R.id.edit).setOnClickListener(this);

		findViewById(R.id.find).setVisibility(View.GONE);
	}

	static boolean enter = true;

	@Override
	protected void onStart() {
		super.onStart();

		if (enter) {
			enter = false;
			Intent i = new Intent(this, AndroidExplorer.class);
			startActivityForResult(i, 0);
		}
	}

	public void fillTextField() {
		try {

			if (file != null) {
				((EditText) findViewById(R.id.edit)).setText("");
				br = new BufferedReader(new FileReader(file));

				while (br.ready()) {
					((EditText) findViewById(R.id.edit)).append(br.readLine());
				}
				((EditText) findViewById(R.id.edit)).setSelection(0);
				br.close();
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(data != null){
			file = new File(data.getExtras().getString("file"));
			fillTextField();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.search:
			findViewById(R.id.find).setVisibility(View.VISIBLE);
			findViewById(R.id.searchField).setVisibility(View.VISIBLE);
			break;
		case R.id.chooseFile:
			enter = false;
			Intent i = new Intent(this, AndroidExplorer.class);
			startActivityForResult(i, 0);			
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onClick(View v) {

		EditText search = ((EditText) findViewById(R.id.searchField));
		String searchString = search.getText().toString();
		sText = text.getText();

		switch (v.getId()) {
		case R.id.searchBtn:

			sText.removeSpan(selectedColor);
			findViewById(R.id.searchField).setVisibility(View.VISIBLE);
			startingPositions.clear();
			currentPosition = -1;
			if (bcs.size() > 0)
				while (!bcs.isEmpty()) {
					sText.removeSpan(bcs.pop());
				}

			String textString = text.getText().toString();

				
				if(((CheckBox)findViewById(R.id.match_case)).isChecked())
					for (int i = 0; i <= textString.length() - searchString.length(); i++) {
						if (textString.substring(i, i + searchString.length())
								.compareTo(searchString) == 0) {
							
							bcs.push(new BackgroundColorSpan(Color.DKGRAY));
							sText.setSpan(bcs.peek(), i, i + search.getText().length(),
									0);
							startingPositions.add(i);
						}
					}
				else
					for (int i = 0; i <= textString.length() - searchString.length(); i++) {
						if (textString.substring(i, i + searchString.length())
								.compareToIgnoreCase(searchString) == 0) {
							
							bcs.push(new BackgroundColorSpan(Color.LTGRAY));
							sText.setSpan(bcs.peek(), i, i + search.getText().length(),
									0);
							startingPositions.add(i);
						}
					}

			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(text.getWindowToken(), 0);

			break;
		case R.id.prevBtn:
			findViewById(R.id.searchField).setVisibility(View.GONE);
			if (startingPositions.size() > 0 && currentPosition > 0) {
				sText.removeSpan(selectedColor);
				sText.setSpan(selectedColor, startingPositions
						.get(--currentPosition), startingPositions
						.get(currentPosition)
						+ searchString.length(), 0);
			}
			break;
		case R.id.nextBtn:
			findViewById(R.id.searchField).setVisibility(View.GONE);
			if (startingPositions.size() > 0
					&& currentPosition < startingPositions.size() - 1) {
				sText.removeSpan(selectedColor);
				sText.setSpan(selectedColor, startingPositions
						.get(++currentPosition), startingPositions
						.get(currentPosition)
						+ searchString.length(), 0);
			}
			break;
		case R.id.edit:
			findViewById(R.id.find).setVisibility(View.GONE);
		}

		text.setText(sText);
		if (currentPosition >= 0)
			text.setSelection(startingPositions.get(currentPosition),
					startingPositions.get(currentPosition)
							+ searchString.length());
	}
	@Override
	public void finish() {
		enter = true;
		super.finish();
	}
}